package eerbaar.v2.gamebuilder.server;

import eerbaar.game.GameFactory;
import eerbaar.game.IGame;
import eerbaar.server.gamebuilder.Builder;
import eerbaar.shared.exceptions.GameException;
import eerbaar.v2.gamebuilder.GamePacket;

public class SERVER {

    public static IGame loadGame(String cookie) throws GameException {

        GamePacket packet = loadGamePacket(cookie);
        IGame game;
        try {

            game = packet.getGame();

        } catch (GameException e) {
            throw e;
        }

        return game;
    }

    public static GamePacket loadGamePacket(String cookie) throws GameException {

        IGame game;
        try {

            if (cookie == null) {

                game = new Builder().buildGame();
            } else {

                game = GameUtil.loadGame(cookie);
            }

        } catch (Throwable t) {

            game = GameFactory.createGame();
        }
        GamePacket packet = packageGame(game);

        return packet;
    }

    public static GamePacket packageGame(IGame game) throws GameException {

        GamePacket packet = new GamePacket();
        packet.setGame(game);

        return packet;
    }

    public static void saveGame(String key, IGame game) throws GameException {

        GameUtil.saveGame(key, game);
    }

    public static IGame unpackageGame(GamePacket packet) throws GameException {

        IGame game = packet.getGame();
        return game;
    }

}
